package com.tg.app.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;

import com.appbase.custom.config.ApiUrl;
import com.appbase.custom.constant.CommonConstants;
import com.magicindicator.buildins.UIUtil;
import com.tange.core.backend.service.ep.HostConfig;
import com.tg.app.BuildConfig;
import com.tg.app.R;
import com.tg.app.activity.base.WebBaseActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.TGGlobalConfigHelper;
import com.tange.base.toolkit.AppUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StatusBarUtil;
import com.tange.base.toolkit.StatusNavUtils;
import com.tange.base.toolkit.StringUtils;
import com.tg.app.util.WebSoftInputHelper;
import com.tg.appcommon.android.TGLog;
import com.tange.core.backend.service.api.CoreApiUrl;
import com.tange.core.backend.service.ep.EnvironmentProxy;

public class CloudServiceActivity extends WebBaseActivity {
    public static final String TAG = "CloudServiceActivity";
    public static final String EXT_CLOUD_SERVICE_TYPE = "ext_cloud_service_type";
    public static final int EXT_CLOUD_SERVICE_TYPE_STORAGEORCAR = 0x001;//云存储
    public static final int EXT_CLOUD_SERVICE_TYPE_AI = 0x002;//ai
    public static final int EXT_CLOUD_SERVICE_TYPE_SIM = 0x003;//ai
    public static final int EXT_CLOUD_SERVICE_TYPE_SUPER_AI = 0x004;//ai super_ai_service
    public static final int EXT_DOORBELL_SERVICE_TYPE_STORAGEORCAR = 0x005;//被动门铃
    public static final int EXT_LOCKBELL_SERVICE_TYPE_STORAGEORCAR = 0x006;//被动门锁
    public static final int EXT_BIRD_FEEDER_SERVICE_TYPE_STORAGEORCAR = 0x007;//喂鸟器
    private int contentMarginTop;

    private RelativeLayout toolbar;

    private ImageButton backBtn;

    @Override
    protected int statusBarColor() {
        return getResources().getColor(R.color.global_customize_fixed_color_light_gray);
    }


    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        removeView();
        super.onBackPressed();
    }

    @SuppressLint("DefaultLocale")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_cloud_service);
        WebSoftInputHelper.assistActivity(this);
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //虚拟键盘也透明
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        hideActionBar();

        toolbar = findViewById(R.id.toolbar);
        backBtn = findViewById(R.id.back_toolbar);
        tvTitle = findViewById(R.id.device_name);
        findViewById(R.id.back_toolbar).setOnClickListener(view -> {
            if (isPayRedirectUrl) {
                mWebview.clearHistory();
                mWebview.loadUrl(mWebUrl);
            } else {
                if (mWebview.canGoBack()) {
                    mWebview.goBack();
                } else {
                    if (mWebUrl != null && mWebUrl.contains(ApiUrl.AUTHENTICATION_PAGE)) {
                        ActivityHelper.gotoDeviceListPage(CloudServiceActivity.this);
                    } else {
                        setResult(RESULT_OK);
                    }
                    removeView();
                    finish();
                }
            }
        });

        mWebview = findViewById(R.id.cloud_service_webview);

        int userId = PreferenceUtil.getInt(this, CommonConstants.PRE_USER_ID);

        try {
            info = getIntent().getParcelableExtra(DeviceSettingsActivity.EXT_DEVICE_INFO);
        }catch (Exception e){
            TGLog.i(TAG, "webveiw getfile: no permission");
        }

        int serviceType = getIntent().getIntExtra(EXT_CLOUD_SERVICE_TYPE, EXT_CLOUD_SERVICE_TYPE_STORAGEORCAR);
        if (serviceType > 0 && info != null) {
            TGLog.i(TAG, "info.id = "  + info.deviceID);
            String serviceStr = "index";
            if (serviceType == EXT_CLOUD_SERVICE_TYPE_AI || serviceType == EXT_CLOUD_SERVICE_TYPE_SUPER_AI) {
                serviceStr = "ai";
                String title = getString(R.string.settings_device_ai);
                String url = TGGlobalConfigHelper.getInstance().getAiServiceDetail();
                if (serviceType == EXT_CLOUD_SERVICE_TYPE_SUPER_AI){
                    String superAiService = TGGlobalConfigHelper.getInstance().getSuperAiService();
                    if (!StringUtils.isEmpty(superAiService)){
                        url = superAiService;
                    }
                }

                if (!StringUtils.isEmpty(url)){
                    createUrl(url, title, userId);
                    return;
                }
            } else if (serviceType == EXT_CLOUD_SERVICE_TYPE_SIM) {
                serviceStr = "sim";
                String title = getString(R.string.settings_device_sim);
                String url = TGGlobalConfigHelper.getInstance().getSimServiceDetail();
                if (!StringUtils.isEmpty(url)){
                    createUrl(url, title, userId);
                    return;
                }
            } else if (serviceType == EXT_CLOUD_SERVICE_TYPE_STORAGEORCAR){
                String url = TGGlobalConfigHelper.getInstance().getStorageServiceDetail();
                if (!StringUtils.isEmpty(url)){
                    createUrl(url, "", userId);
                    return;
                }
            } else if (serviceType == EXT_DOORBELL_SERVICE_TYPE_STORAGEORCAR){
                String url = TGGlobalConfigHelper.getInstance().getStorageServiceDetailDoorbell();
                if (!StringUtils.isEmpty(url)){
                    createUrl(url, "", userId);
                    return;
                }
            } else if (serviceType == EXT_LOCKBELL_SERVICE_TYPE_STORAGEORCAR){
                String url = TGGlobalConfigHelper.getInstance().getLockbellServiceDetail();
                if (!StringUtils.isEmpty(url)){
                    createUrl(url, "", userId);
                    return;
                }
            } else if (serviceType == EXT_BIRD_FEEDER_SERVICE_TYPE_STORAGEORCAR){
                String url = TGGlobalConfigHelper.getInstance().getBirdfeederServiceDetail();
                if (!StringUtils.isEmpty(url)){
                    createUrl(url, "", userId);
                    return;
                }
            }
            // 避免拼多了一个 /
            String hostUrl = CoreApiUrl.TG_HOST;
            if (BuildConfig.DEBUG){
           //     hostUrl = HostConfig.HOST_TEST;
            }
            if (hostUrl.endsWith("/")) {
                hostUrl = hostUrl.substring(0, hostUrl.length() - 1);
            }
            mWebUrl = String.format("%s/shop/%s?user_id=%d&device_id=%d", hostUrl, serviceStr, userId, info.deviceID, AppUtil.getVersionName(this));

            if (serviceType == EXT_CLOUD_SERVICE_TYPE_SIM) {
                mWebUrl = String.format("%s&uuid=%s", mWebUrl, info.uuid);
            }
            if (TextUtils.isEmpty(mWebUrl)) return;

            TGLog.d("mWeburl =" + mWebUrl);
            initWeb();
            modifyToolBar();

            // 设置顶头的间距
            setToolBarMargin();

            setContentFullScreen(false);
        } else {
            String url = getIntent().getStringExtra(KEY_WEBURL);
            String title = getIntent().getStringExtra(KEY_WEBTITLE);
            createUrl(url, title, userId);
        }

    }

    private void createUrl(String url, String title, int userId){
        tvTitle.setText(title);
        EnvironmentProxy.initStatic();
        String host = CoreApiUrl.TG_STATIC;
        if (BuildConfig.DEBUG){
          //  host = HostConfig.STATIC_TEST;
        }
        if (!TextUtils.isEmpty(url)) {
            if (!(url.startsWith("http://") || url.startsWith("https://"))) {
                if (url.startsWith("/#/")){
                    url = url.replace("/#/","#/");
                }

                // 避免多拼了一个"/"
                if (host.endsWith("/") && url.startsWith("/")) {
                    url = url.substring(1);
                }

                mWebUrl = String.format("%s%s", host, url);
            } else {
                mWebUrl = url;
            }
            Uri.Builder builder =  Uri.parse(mWebUrl).buildUpon();
            builder.appendQueryParameter("user_id",String.valueOf(userId));
            if (info != null) {
                builder.appendQueryParameter("device_id",String.valueOf(info.deviceID));
                if (!TextUtils.isEmpty(info.uuid)){
                    builder.appendQueryParameter("uuid",info.uuid);
                }

                if (info.orderId != -1){
                    builder.appendQueryParameter("id", String.valueOf(info.orderId));
                }
            }

            if (!StringUtils.isEmpty(title)){
                builder.appendQueryParameter("title", title);
            }
            mWebUrl =  builder.toString();
        } else {
            mWebUrl = redirecUrl;
        }
        if (TextUtils.isEmpty(mWebUrl)) return;

        TGLog.d(TAG,"mWeburl =" + mWebUrl);
        Log.i(TAG,"mWeburl" + mWebUrl);
        Log.e(TAG,"mWeburl" + mWebUrl);
        initWeb();
        modifyToolBar();

        // 设置顶头的间距
        setToolBarMargin();

        setContentFullScreen(false);
    }

    @Override
    protected void updateStatusBarTextColor(boolean dark) {
        StatusBarUtil.setLightStatusBar(this, dark);
    }

    @Override
    protected int getContentMarginTop() {
        return contentMarginTop;
    }

    @Override
    protected void updateStatusBarColor(String colorStr) {
        int color = -1;
        try {
            color = Color.parseColor(colorStr);
        } catch (Throwable ignored) {}

        if (color == -1) {
            return;
        }

        StatusNavUtils.setStatusBarColor(CloudServiceActivity.this, color);
    }

    @Override
    protected void updateToolBarTextColor(String colorStr) {
        int color = -1;
        try {
            color = Color.parseColor(colorStr);
        } catch (Throwable ignored) {}

        if (color == -1) {
            return;
        }
        tvTitle.setTextColor(color);
    }

    @Override
    protected void updateToolBarBackgroundColor(String colorStr) {
        int color = -1;
        try {
            color = Color.parseColor(colorStr);
        } catch (Throwable ignored) {}

        if (color == -1) {
            return;
        }

        toolbar.setBackgroundColor(color);
    }

    @Override
    protected void updateBackBtnColor(boolean useWhite) {
        backBtn.setImageResource(useWhite ? R.drawable.ic_back_btn_white : R.drawable.ic_back_btn);
    }

    @Override
    protected void setContentFullScreen(boolean fullScreen) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mWebview.getLayoutParams();
        lp.topMargin = fullScreen ? 0 : contentMarginTop;
        mWebview.setLayoutParams(lp);
    }

    private void setToolBarMargin() {
        int statusBarHeight = getStatusBarHeight(this);
        View toolBar = findViewById(R.id.toolbar);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) toolBar.getLayoutParams();
        lp.topMargin = statusBarHeight;
        toolBar.setLayoutParams(lp);

        contentMarginTop = statusBarHeight + UIUtil.dip2px(this, 50);
    }

    private static int getStatusBarHeight(Context context) {
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(new int[]{
                android.R.attr.windowFullscreen
        });
        boolean windowFullscreen = typedArray.getBoolean(0, false);
        typedArray.recycle();

        if (windowFullscreen) {
            return 0;
        }

        int height = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            height = context.getResources().getDimensionPixelSize(resourceId);
        }
        return height;
    }

    private void loadPay() {
        if (!TextUtils.isEmpty(redirecUrl)) {
            mWebview.loadUrl(redirecUrl);
            redirecUrl = "";
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        loadPay();
    }

    public void setBackButton(boolean show){
        if (backBtn != null){
            backBtn.setVisibility(show? View.VISIBLE : View.GONE);
        }
    }
}
